package com.yupi.springbootinit.manager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.yupi.springbootinit.constant.BigModelConstant;
import com.yupi.springbootinit.utils.ImageUtil;
import okhttp3.*;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.CountDownLatch;

public class BigModelPicture extends WebSocketListener {

    public static final String hostUrl = "http://spark-api.cn-huabei-1.xf-yun.com/v2.1/image";
    public static final String appid = BigModelConstant.APPID;
    public static final String apiSecret = BigModelConstant.APISECRET;
    public static final String apiKey = BigModelConstant.APIKEY;

    private List<RoleContent> historyList = new ArrayList<>();
    private String totalAnswer = "";
    private Boolean ImageAddFlag = false;
    private final Gson gson = new Gson();
    private String userId;
    private Boolean wsCloseFlag;
    private String imagePath;
    private CountDownLatch latch = new CountDownLatch(1);
    private String finalAnswer;

    public BigModelPicture(String userId, String imagePath) {
        this.userId = userId;
        this.imagePath = imagePath;
        this.wsCloseFlag = false;
    }

    public String generateAnswer(String newQuestion) throws Exception {
        this.finalAnswer = null;
        String authUrl = getAuthUrl(hostUrl, apiKey, apiSecret);
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();

        WebSocket webSocket = client.newWebSocket(request, this);
        this.new ThreadRunner(webSocket, newQuestion).start();

        latch.await(); // 等待异步响应完成
        return finalAnswer;
    }

    class ThreadRunner extends Thread {
        private WebSocket webSocket;
        private String question;

        public ThreadRunner(WebSocket webSocket, String question) {
            this.webSocket = webSocket;
            this.question = question;
        }

        public void run() {
            try {
                JSONObject requestJson = new JSONObject();

                JSONObject header = new JSONObject();
                header.put("app_id", appid);
                header.put("uid", UUID.randomUUID().toString().substring(0, 10));

                JSONObject parameter = new JSONObject();
                JSONObject chat = new JSONObject();
                chat.put("domain", "imagev3");
                chat.put("temperature", 0.5);
                chat.put("max_tokens", 4096);
                chat.put("auditing", "default");
                parameter.put("chat", chat);

                JSONObject payload = new JSONObject();
                JSONObject message = new JSONObject();
                JSONArray text = new JSONArray();

                // 添加历史记录
                synchronized (historyList) {
                    if (!historyList.isEmpty()) {
                        historyList.forEach(rc -> text.add(JSON.toJSON(rc)));
                    }
                }

                // 添加图片信息
                RoleContent imageContent = new RoleContent();
                imageContent.role = "user";


                imageContent.content = Base64.getEncoder().encodeToString(ImageUtil.read(imagePath));
                imageContent.content_type = "image";
                text.add(JSON.toJSON(imageContent));

                // 添加问题
                RoleContent questionContent = new RoleContent();
                questionContent.role = "user";
                questionContent.content = question;
                questionContent.content_type = "text";
                text.add(JSON.toJSON(questionContent));

                // 更新历史记录
                synchronized (historyList) {
                    historyList.add(imageContent);
                    historyList.add(questionContent);
                    while (historyList.size() > 10) { // 保持最近10条历史
                        historyList.remove(0);
                    }
                }

                message.put("text", text);
                payload.put("message", message);

                requestJson.put("header", header);
                requestJson.put("parameter", parameter);
                requestJson.put("payload", payload);

                webSocket.send(requestJson.toString());

                // 等待响应
                while (!wsCloseFlag) {
                    Thread.sleep(200);
                }
                webSocket.close(1000, "");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
        if (myJsonParse.header.code != 0) {
            System.err.println("Error Code: " + myJsonParse.header.code);
            latch.countDown();
            return;
        }

        StringBuilder answerBuilder = new StringBuilder();
        myJsonParse.payload.choices.text.forEach(t -> answerBuilder.append(t.content));
        totalAnswer += answerBuilder.toString();

        if (myJsonParse.header.status == 2) {
            synchronized (historyList) {
                RoleContent answerContent = new RoleContent();
                answerContent.role = "assistant";
                answerContent.content = totalAnswer;
                answerContent.content_type = "text";
                historyList.add(answerContent);
            }
            this.finalAnswer = totalAnswer;
            wsCloseFlag = true;
            latch.countDown();
        }
    }

    @Override
    public void onFailure(WebSocket webSocket, Throwable t, Response response) {
        System.err.println("Connection failed: " + t.getMessage());
        latch.countDown();
    }

    // 鉴权方法
    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        // 时间
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());
        // 拼接
        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";
        // System.err.println(preStr);
        // SHA256加密
        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        // Base64加密
        String sha = Base64.getEncoder().encodeToString(hexDigits);
        // System.err.println(sha);
        // 拼接
        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"", apiKey, "hmac-sha256", "host date request-line", sha);
        // 拼接地址
        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder().//
                addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8))).//
                addQueryParameter("date", date).//
                addQueryParameter("host", url.getHost()).//
                build();

        // System.err.println(httpUrl.toString());
        return httpUrl.toString();
    }

    //返回的json结果拆解
    class JsonParse {
        BigModelPicture.Header header;
        BigModelPicture.Payload payload;
    }

    class Header {
        int code;
        int status;
        String sid;
    }

    class Payload {
        BigModelPicture.Choices choices;
    }

    class Choices {
        List<BigModelPicture.Text> text;
    }

    class Text {
        String role;
        String content;
    }
    class RoleContent{
        String role;
        String content;

        String content_type;

        public String getContent_type() {
            return content_type;
        }

        public void setContent_type(String content_type) {
            this.content_type = content_type;
        }

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }
}